package accs.product.update;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import accs.product.CryptUtils;

public class Updater {
	private static final String VERSION_CHECK_URL="checker/version.php";
	public static final String INTERACTIVE_UPDATE_URL="checker/";
	public static final String AUTOMATIC_UPDATE_URL="checker/hermes.zip";
	
	public Updater() {
	}
	
	/**
	 * 
	 * @return a version object if an update is available, otherwise null
	 * @throws Exception
	 */
	public Version checkForUpdate() throws Exception {
		DefaultHttpClient client=new DefaultHttpClient();
		
		HttpGet get=new HttpGet(VERSION_CHECK_URL);
		
		HttpEntity ent=client.execute(get).getEntity();
		
		byte[] result=EntityUtils.toByteArray(ent);
		if(result[0]==-17 && result[1]==-69 && result[2]==-65) { //BOM entfernen
			result=Arrays.copyOfRange(result,3,result.length); //System.out.println("Updater BOM");
		}
		Version serverVersion=new Version(CryptUtils.decrypt(new String(result))); //System.out.println(serverVersion);
		
		if(serverVersion.compareTo(Version.CURRENT_VERSION)>0) {
			return serverVersion;
		} else {
			return null;
		}
	}
	
	public void downloadAndUnpack(File targetFolder) throws MalformedURLException, IOException {
		downloadAndUnpack(targetFolder,null);
	}
	
	public void downloadAndUnpack(File targetFolder, UpdateListener listener) throws MalformedURLException, IOException {
		
		DefaultHttpClient client=new DefaultHttpClient();
		InputStream stream=client.execute(new HttpGet(AUTOMATIC_UPDATE_URL)).getEntity().getContent();
		
		ZipInputStream in=new ZipInputStream(stream);
		//ZipInputStream in=new ZipInputStream(new File("hermes.zip").toURI().toURL().openStream());
		ZipEntry entry=null;
		
		byte[] buffer=new byte[8*1024];
		int read=0;
		
		targetFolder.mkdir();
		
		while((entry=in.getNextEntry())!=null) {
			if(listener!=null) listener.update(entry.getName());
			
			File file=new File(targetFolder,entry.getName());
			
			if(entry.isDirectory()) {
				file.mkdir();
			} else {
				BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(file));
				
				while((read=in.read(buffer))!=-1) {
					out.write(buffer,0,read);
				}
				
				out.close();
			}
			
			in.closeEntry();
		}
		
		in.close();
	}
	
//	public static void main(String[] args) throws MalformedURLException, IOException {
//		new Updater().downloadAndUnpack(new File("c:\\temp\\hermes"));
//	}
}